package css.sword.util;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import com.sun.star.awt.Size;
import com.sun.star.beans.PropertyValue;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.view.PaperFormat;
import com.sun.star.view.XPrintable;
import org.jodconverter.OfficeDocumentConverter;
import org.jodconverter.office.DefaultOfficeManagerBuilder;
import org.jodconverter.office.OfficeException;
import org.jodconverter.office.OfficeManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LibreUtils {
    private static String officeHomeDir = null;

    private final static Logger logger = LoggerFactory.getLogger(LibreUtils.class);

    public final static Size A5, A4, A3;
    public final static Size B4, B5, B6;
    public final static Size KaoqinReport;
    private final static  OfficeManager officeManager;
    static {

        String libreOfficePath = getOfficeHome();

        DefaultOfficeManagerBuilder builder = new DefaultOfficeManagerBuilder();
        builder.setOfficeHome(new File(libreOfficePath));

        // 端口号
        builder.setPortNumbers(8100);
        builder.setTaskExecutionTimeout(1000 * 60 * 5L);
        // 设置任务执行超时为5分钟
        builder.setTaskQueueTimeout(1000 * 60 * 60 * 24L);
        // 设置任务队列超时为24小时

        officeManager = builder.build();
        startService(officeManager);

        A5 = new Size(14800, 21000);
        A4 = new Size(21000, 29700);
        A3 = new Size(29700, 42000);

        B4 = new Size(25000, 35300);
        B5 = new Size(17600, 25000);
        B6 = new Size(12500, 17600);
        KaoqinReport = new Size(29700, 27940);  //最大限度  宽 1600000
    }

    /**
     *
     *@name    文档转换为pdf工具类
     *@description 相关说明 支持：xls，xlsx，ppt，pptx，txt，其中doc，docx转换与原文件有较大差异,libreOffice 默认安装路径
     *Linux：/opt/libreoffice6.0
     *Windows：C:/Program Files (x86)/LibreOffice
     *Mac：/Application/openOfficeSoft
     *@time    创建时间:2018年9月17日下午1:49:18
     *@param sourceFile 需要转换的原文件
     *@param tarPdfFile 转换后的目标pdf文件
     *@return
     *@throws OfficeException
     *@author   祥保玉
     *@history 修订历史（历次修订内容、修订人、修订时间等）
     */
    public static File doDocToFdpLibre(File sourceFile, File tarPdfFile) {


        if (!sourceFile.exists()) {
            logger.error("office转换服务启动失败!文件不存在:{}", sourceFile);
            return null;
        }

        PropertyValue[] printerDesc = new PropertyValue[2];

        // Paper Orientation
        //  printerDesc[0] = new PropertyValue();
        //  printerDesc[0].Name = "PaperOrientation";
        //  printerDesc[0].Value = PaperOrientation.PORTRAIT;

        // Paper Format
//        printerDesc[0] = new PropertyValue();
//        printerDesc[0].Name = "PaperFormat";
//        printerDesc[0].Value = PaperFormat.USER;
//
//        // Paper Size
//        printerDesc[1] = new PropertyValue();
//        printerDesc[1].Name = "PaperSize";
//        printerDesc[1].Value = KaoqinReport;


//            if (!officeManager.isRunning()) {
//                startService(officeManager);
//            }
       // XPrintable xPrintable = (XPrintable) UnoRuntime.queryInterface(XPrintable.class, document);
        OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);

        try {
            Map map=new HashMap();
            map.put("PaperSize",KaoqinReport);
            map.put("PaperFormat",PaperFormat.USER);
            converter.setDefaultLoadProperties(map);
            converter.convert(sourceFile, tarPdfFile);

        } catch (Exception e) {
            logger.error("office转换失败!详细信息:{}", e);
//            try {
//               // stopService(officeManager);
//                ;
//            } catch (OfficeException emsg) {
//                logger.error("office LibreOffice 关闭失败，详细信息：{}", emsg);
//            }

        }
        return tarPdfFile;
    }

    private static String getOfficeHome() {

        if (null != officeHomeDir) {
            return officeHomeDir;
        } else {
            String osName = System.getProperty("os.name");
            if (Pattern.matches("Windows.*", osName)) {
                officeHomeDir = "C:\\Program Files\\LibreOffice";
                return officeHomeDir;
            } else if (Pattern.matches("Linux.*", osName)) {
                officeHomeDir = "/opt/libreoffice6.0";
                return officeHomeDir;
            } else if (Pattern.matches("Mac.*", osName)) {
                officeHomeDir = "/Application/openOfficeSoft";
                return officeHomeDir;
            }
            return null;
        }

    }

    private static void stopService(OfficeManager officeManager) throws OfficeException {
        if (null != officeManager) {
            officeManager.stop();
        }
        logger.info("关闭office转换成功!");
    }

    private static void startService(OfficeManager officeManager) {

        try {
            // 准备启动服务
            officeManager.start(); // 启动服务
            logger.info("office转换服务启动成功");
        } catch (Exception ce) {
            logger.error("office转换服务启动失败!详细信息:{}", ce);
        }
    }

    /**
     *
     *@name    设置libreOffice安装目录
     *@description 相关说明：如果libreOffice安装目录为默认目录，则不需要设置，否则需要设置
     *@time    创建时间:2018年9月17日下午1:52:36
     *@param officeHome
     *@author   作者
     *@history 修订历史（历次修订内容、修订人、修订时间等）
     */
    public static void setOfficeHome(String officeHome) {
        officeHomeDir = officeHome;
    }

    public static void main(String[] args){

//        System.out.println();
//        doDocToFdpLibre("C:\\Users\\12555\\Desktop\\szoa架构组项目周报-20180914.xlsx","C:\\Users\\12555\\Desktop\\LJW.pdf");
//        long startTime=System.currentTimeMillis();
//        doDocToFdpLibre("C:\\Users\\12555\\Desktop\\document.html","C:\\Users\\12555\\Desktop\\LJW1.pdf");
//        System.out.println(System.currentTimeMillis()-startTime);
    }
}
